package org.dbstar.scheduler.control;

import org.dbstar.scheduler.beans.Job;
import org.dbstar.scheduler.beans.JobConf;
import org.dbstar.scheduler.control.exception.DaoException;
import org.dbstar.scheduler.job.JobStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 用于更新JobConf的平均执行耗时
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-6-4
 */
public class JobConfAverageRunTimeUpdater implements JobStatusChangeListener {
	private static final Logger LOGGER = LoggerFactory.getLogger(JobConfAverageRunTimeUpdater.class);
	private final JobConfController jobConfController;

	public JobConfAverageRunTimeUpdater(JobController jobController, JobConfController jobConfController) {
		super();
		this.jobConfController = jobConfController;
		// 注册监听器
		jobController.registJobStatusChangeListener(this, null, null, JobStatus.finish);
	}

	@Override
	public void onJobStatusChange(Job job, JobStatus oldStatus, JobStatus newStatus) {
		if (JobStatus.finish == newStatus) {
			try {
				JobConf conf = jobConfController.getJobConf(job.getJobConfIdentifier());
				if (conf != null) {
					synchronized (conf) {
						int art = conf.getAverageRunTime();
						long time = job.getFinishTime() - job.getLaunchTime();
						int newArt = (int) (art < 0 ? time : ((art * 30 + time) / 31));
						jobConfController.updateJobConfAverageRunTime(job.getJobConfIdentifier(), newArt);
					}
				}
			} catch (DaoException e) {
				LOGGER.error("更新JobConf的平均执行耗时失败。", e);
			}
		}
	}
}
